'''oto/deck.py

This module contains the Deck class.
'''

__authors__ = ['Ryan Rousseau <ryan.rousseau@gmail.com>']
__license__ = '''Oranges to Oranges
Copyright (C) 2006  Ryan Rousseau

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
'''


import random
import shelve

__all__ = ['Deck']

class Deck(object):
    def __init__(self, name):
        self.name = name
        self.nouns = []
        self.adjs = []

        filename = name
        f = shelve.open(filename)
        for key in f:
            title = key[2:]
            text = f[key]
            if key.startswith('a_'):
                self.adjs.append(Card(title, text))
            elif key.startswith('n_'):
                self.nouns.append(Card(title, text))

    def shuffle(self):
        random.shuffle(self.nouns)
        random.shuffle(self.adjs)

    def draw_noun(self):
        return self.nouns.pop(0)

    def draw_adj(self):
        return self.adjs.pop(0)

    def add_noun(self, noun):
        self.nouns.append(noun)

    def add_adj(self, adj):
        self.adjs.append(adj)

    def save(self):
        filename = self.name
        f = shelve.open(filename)

        for adj in self.adjs:
            key = 'a_%s' % adj.title
            f[key] = adj.extra

        for noun in self.nouns:
            key = 'n_%s' % noun.title
            f[key] = noun.extra

        f.close()
